<template>
  <view class="staff-edit-page">
    <!-- 表单内容 -->
    <view class="form-content">
      <u-form :model="formData" :rules="rules" ref="formRef" label-width="120rpx">
        <!-- 基本信息 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="user" color="#667eea" size="16"></u-icon>
            <text>基本信息</text>
          </view>
          
          <u-form-item label="真实姓名" prop="realName" required>
            <u-input 
              v-model="formData.realName"
              placeholder="请输入真实姓名"
              maxlength="50"
              class="form-input"
            />
          </u-form-item>
          
          <u-form-item label="工号" prop="employeeNo" required>
            <u-input 
              v-model="formData.employeeNo"
              placeholder="请输入工号"
              maxlength="20"
              class="form-input"
            />
          </u-form-item>
          
          <u-form-item label="手机号" prop="phone" required>
            <u-input 
              v-model="formData.phone"
              placeholder="请输入手机号"
              type="number"
              maxlength="11"
              class="form-input"
            />
          </u-form-item>
          
          <u-form-item label="邮箱" prop="email">
            <u-input 
              v-model="formData.email"
              placeholder="请输入邮箱"
              type="email"
              class="form-input"
            />
          </u-form-item>
        </view>
        
        <!-- 工作信息 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="briefcase" color="#667eea" size="16"></u-icon>
            <text>工作信息</text>
          </view>
          
          <u-form-item label="物业公司" prop="propertyCompanyId" required>
            <u-input 
              v-model="formData.propertyCompanyName"
              placeholder="请选择物业公司"
              readonly
              @click="showPropertyCompanyPicker = true"
              class="form-input"
            />
          </u-form-item>
          
          <u-form-item label="职位" prop="position" required>
            <u-input 
              v-model="formData.position"
              placeholder="请输入职位"
              maxlength="50"
              class="form-input"
            />
          </u-form-item>
          
          <u-form-item label="入职日期" prop="entryDate" required>
            <u-input 
              v-model="formData.entryDate"
              placeholder="请选择入职日期"
              readonly
              @click="showDatePicker = true"
              class="form-input"
            />
          </u-form-item>
          
          <u-form-item label="员工状态" prop="status" required>
            <u-radio-group v-model="formData.status" direction="row">
              <u-radio 
                v-for="item in statusOptions" 
                :key="item.value" 
                :name="item.value"
                :label="item.label"
              />
            </u-radio-group>
          </u-form-item>
        </view>
        
        <!-- 头像设置 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="camera" color="#667eea" size="16"></u-icon>
            <text>头像设置</text>
          </view>
          
          <AppImageUpload
            v-model="avatarList"
            title="员工头像"
            tip="请上传员工头像，支持jpg、jpeg、png格式，最大2MB"
            :required="false"
            :max-count="1"
            :max-size="2"
            :allowed-types="['jpg', 'jpeg', 'png']"
            @success="handleAvatarSuccess"
            @error="handleAvatarError"
          />
        </view>
      </u-form>
    </view>
    
    <!-- 底部操作按钮 -->
    <view class="action-section">
      <u-button 
        type="default" 
        text="取消"
        size="large"
        @click="handleCancel"
        class="action-button"
      />
      <u-button 
        type="primary" 
        text="保存"
        size="large"
        @click="handleSubmit"
        :loading="submitting"
        class="action-button"
      />
    </view>
    
    <!-- 日期选择器 -->
    <u-datetime-picker
      :show="showDatePicker"
      v-model="selectedDate"
      mode="date"
      :min-date="minDate"
      :max-date="maxDate"
      @confirm="handleDateConfirm"
      @cancel="showDatePicker = false"
    />
  </view>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import AppImageUpload from '@/components/AppImageUpload.vue'
import { staffApi } from '@/api/staff'

export default {
  name: 'StaffEdit',
  components: {
    AppImageUpload
  },
  setup() {
    // 响应式数据
    const formRef = ref(null)
    const submitting = ref(false)
    const loading = ref(false)
    const showDatePicker = ref(false)
    const selectedDate = ref(new Date().getTime())
    const avatarList = ref([])
    const staffId = ref('')
    
    // 日期范围
    const minDate = new Date(2020, 0, 1).getTime()
    const maxDate = new Date().getTime()
    
    // 表单数据
    const formData = reactive({
      realName: '',
      employeeNo: '',
      phone: '',
      email: '',
      department: '',
      position: '',
      entryDate: '',
      status: 1
    })
    
    // 状态选项
    const statusOptions = ref([
      { label: '在职', value: 1 },
      { label: '离职', value: 0 },
      { label: '待入职', value: 2 }
    ])
    
    // 表单验证规则
    const rules = {
      realName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' },
        { min: 2, max: 50, message: '姓名长度在2-50个字符之间', trigger: 'blur' }
      ],
      employeeNo: [
        { required: true, message: '请输入工号', trigger: 'blur' },
        { min: 2, max: 20, message: '工号长度在2-20个字符之间', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      email: [
        { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      department: [
        { required: true, message: '请输入部门', trigger: 'blur' },
        { min: 2, max: 50, message: '部门名称长度在2-50个字符之间', trigger: 'blur' }
      ],
      position: [
        { required: true, message: '请输入职位', trigger: 'blur' },
        { min: 2, max: 50, message: '职位名称长度在2-50个字符之间', trigger: 'blur' }
      ],
      entryDate: [
        { required: true, message: '请选择入职日期', trigger: 'change' }
      ],
      status: [
        { required: true, message: '请选择员工状态', trigger: 'change' }
      ]
    }
    
    // 加载员工信息
    const loadStaffInfo = async () => {
      try {
        loading.value = true
        
        // 调用后端API获取员工信息
        const response = await staffApi.getStaffDetail(staffId.value)
        
        if (response && response.code === 200 && response.data) {
          const staffData = response.data
          
          // 填充表单数据
          Object.assign(formData, {
            realName: staffData.realName || '',
            employeeNo: staffData.employeeNo || '',
            phone: staffData.phone || '',
            email: staffData.email || '',
            department: staffData.department || '',
            position: staffData.position || '',
            entryDate: staffData.entryDate || '',
            status: staffData.status || 1
          })
          
          // 设置头像
          if (staffData.avatar) {
            avatarList.value = [{ fileUrl: staffData.avatar }]
          }
        } else {
          // API调用失败，使用模拟数据
          console.warn('API调用失败，使用模拟数据')
          const mockData = {
            realName: '张三',
            employeeNo: 'EMP001',
            phone: '13800138000',
            email: 'zhangsan@example.com',
            department: '维修部',
            position: '维修工',
            entryDate: '2023-01-15',
            status: 1,
            avatar: ''
          }
          
          // 填充表单数据
          Object.assign(formData, mockData)
          
          // 设置头像
          if (mockData.avatar) {
            avatarList.value = [{ fileUrl: mockData.avatar }]
          }
        }
        
      } catch (error) {
        console.error('加载员工信息失败:', error)
        
        // 网络错误时使用模拟数据
        const mockData = {
          realName: '张三',
          employeeNo: 'EMP001',
          phone: '13800138000',
          email: 'zhangsan@example.com',
          department: '维修部',
          position: '维修工',
          entryDate: '2023-01-15',
          status: 1,
          avatar: ''
        }
        
        // 填充表单数据
        Object.assign(formData, mockData)
        
        // 设置头像
        if (mockData.avatar) {
          avatarList.value = [{ fileUrl: mockData.avatar }]
        }
        
        uni.showToast({
          title: '网络异常，显示模拟数据',
          icon: 'none'
        })
      } finally {
        loading.value = false
      }
    }
    
    // 日期确认
    const handleDateConfirm = (value) => {
      const date = new Date(value)
      formData.entryDate = date.toLocaleDateString('zh-CN')
      showDatePicker.value = false
    }
    
    // 头像上传成功
    const handleAvatarSuccess = (data) => {
      console.log('头像上传成功:', data)
      uni.showToast({
        title: '头像上传成功',
        icon: 'success'
      })
    }
    
    // 头像上传失败
    const handleAvatarError = (error) => {
      console.error('头像上传失败:', error)
      uni.showToast({
        title: '头像上传失败',
        icon: 'error'
      })
    }
    
    // 表单提交
    const handleSubmit = async () => {
      try {
        // 表单验证
        const valid = await formRef.value.validate()
        if (!valid) return
        
        submitting.value = true
        
        // 准备提交数据
        const submitData = {
          ...formData,
          avatar: avatarList.value.length > 0 ? avatarList.value[0].fileUrl : ''
        }
        
        console.log('提交员工数据:', submitData)
        
        // 调用后端API更新员工信息
        const response = await staffApi.updateStaff(staffId.value, submitData)
        
        if (response && response.code === 200) {
          uni.showToast({
            title: '员工信息更新成功',
            icon: 'success'
          })
          
          // 返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          throw new Error(response?.message || '更新失败')
        }
        
      } catch (error) {
        console.error('提交失败:', error)
        uni.showToast({
          title: error.message || '提交失败，请重试',
          icon: 'error'
        })
      } finally {
        submitting.value = false
      }
    }
    
    // 取消操作
    const handleCancel = () => {
      uni.showModal({
        title: '确认取消',
        content: '确定要取消编辑员工吗？未保存的数据将丢失。',
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack()
          }
        }
      })
    }
    
    // 页面加载
    onMounted(() => {
      // 获取页面参数
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1]
      staffId.value = currentPage.options.id || ''
      
      if (staffId.value) {
        loadStaffInfo()
      } else {
        uni.showToast({
          title: '员工ID不能为空',
          icon: 'error'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    })
    
    return {
      formRef,
      submitting,
      loading,
      showDatePicker,
      selectedDate,
      minDate,
      maxDate,
      avatarList,
      formData,
      statusOptions,
      rules,
      handleDateConfirm,
      handleAvatarSuccess,
      handleAvatarError,
      handleSubmit,
      handleCancel
    }
  }
}
</script>

<style lang="scss" scoped>
.staff-edit-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.form-content {
  flex: 1;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 40rpx;
  
  .section-title {
    display: flex;
    align-items: center;
    gap: 8rpx;
    margin-bottom: 20rpx;
    font-size: 30rpx;
    font-weight: 600;
    color: #333;
    
    .required {
      color: #f56c6c;
      font-weight: bold;
    }
  }
}

.form-input {
  background: #f8f9fa;
  border-radius: 8rpx;
}

.action-section {
  display: flex;
  gap: 20rpx;
  padding: 20rpx;
  background: white;
  border-top: 1rpx solid #f0f0f0;
  
  .action-button {
    flex: 1;
  }
}

/* 响应式适配 */
@media screen and (max-width: 375px) {
  .form-content {
    margin: 15rpx;
    padding: 20rpx;
  }
  
  .form-section {
    margin-bottom: 30rpx;
  }
}
</style>
